//
//  CoolUtil.m
//  CoolFramework
//
//  Created by xue fei on 11-9-14.
//  Copyright 2011年 FelixApp. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import <CommonCrypto/CommonHMAC.h>
#import <CoreText/CoreText.h>

#import "CoolUtil.h"

//static  UIViewController    *sRootViewController = nil;

@implementation CoolUtil

+ (UIImage*)snapImageOfView:(UIView*)aView {
    UIGraphicsBeginImageContextWithOptions(aView.bounds.size, aView.opaque, 0.0);
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -aView.bounds.origin.x, -aView.bounds.origin.y);
    [aView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

+ (NSString*)mbStringForSize:(double)size {
    double mbSize = size/1024.0/1024.0;
    if (mbSize < 1) {
        return @"小于1MB";
    } else {
        return [NSString stringWithFormat:@"%.1fMB", mbSize];
    }
}

+ (NSString*)kbStringForSize:(double)size {
    double kbSize = size/1024.0;
    if (kbSize < 1) {
        return @"小于1KB";
    } else {
        return [NSString stringWithFormat:@"%.0fKB", kbSize];
    }
}

+ (NSString*)pathForUrl:(NSURL*)url {
    NSArray *pathComponents = [url pathComponents];
    NSMutableString *directoryStr = [NSMutableString string];
    if (pathComponents && pathComponents.count>1) {
        for (NSUInteger index = 0; index < (pathComponents.count-1); index++) {
            NSString *aComponent = [pathComponents objectAtIndex:index];
            if (![@"/" isEqualToString:aComponent]) {
                [directoryStr appendString:@"/"];
                [directoryStr appendString:aComponent];
            }
        }
    } else {
        directoryStr = [NSMutableString stringWithString:@""];
    }
    return directoryStr;
}

//更改图片尺寸
+ (UIImage *)reSizeImage:(UIImage *)image aspectToFitSize:(CGSize)size scale:(CGFloat)scale {
    CGSize reSize = size;
    if (size.width / size.height > image.size.width / image.size.height) {
        reSize.width = image.size.width * size.height / image.size.height;
    } else {
        reSize.height = image.size.height * size.width / image.size.width;
    }
    return [CoolUtil reSizeImage:image toSize:reSize scale:scale];
}

+ (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize scale:(CGFloat)scale
{
    if (image.size.width < reSize.width+0.5 && image.size.width > reSize.width-0.5 && image.size.height < reSize.height+0.5&& image.size.height > reSize.height-0.5) {
        return image;
    }
	UIGraphicsBeginImageContextWithOptions(CGSizeMake(reSize.width, reSize.height), NO, scale);
	[image drawInRect:CGRectMake(0, 0, reSize.width,reSize.height)];
	UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return reSizeImage;
}

+ (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize cropToSize:(CGSize)croppedSize
{
    if (image.size.width < reSize.width+0.5 && image.size.width > reSize.width-0.5 && image.size.height < reSize.height+0.5&& image.size.height > reSize.height-0.5) {
        return image;
    }
    UIGraphicsBeginImageContextWithOptions(croppedSize, NO, 0.0);
	[image drawInRect:CGRectMake(0, 0, reSize.width,reSize.height)];
	UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return reSizeImage;
}

+ (UIImage *)clipImage:(UIImage *)originalImage toRect:(CGRect)cropRect {
    if (!originalImage) {
        return nil;
    }
    CGFloat scale = [UIScreen mainScreen].scale;
    cropRect = CGRectMake(cropRect.origin.x*scale, cropRect.origin.y*scale, cropRect.size.width*scale, cropRect.size.height*scale);
    CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    CFRelease(imageRef);
    return image;
}

+ (NSString*)cachesPathByAppendingPathComponent:(NSString*)pathComponent {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];//documents路径
    return [documentsDirectory stringByAppendingPathComponent:pathComponent];
}

+ (NSString*)pathForImageName:(NSString*)imageName ofType:(NSString*)type inBundle:(NSBundle*)bundle {
    NSUInteger scale = [UIScreen mainScreen].scale;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (scale > 1) {
        NSString* retinaPath = [bundle pathForResource:[imageName stringByAppendingString:@"@2x"] ofType:type];
        
        if ([fileManager fileExistsAtPath:retinaPath]) {
            return retinaPath;
        }
    }
    NSString* path = [bundle pathForResource:imageName ofType:type];
    
    if ([fileManager fileExistsAtPath:path]) {
        return path;
    }
    return nil;
}

+ (NSDate*)dateFromString:(NSString*)dateString withFormat:(NSString*)format {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:format];
    return [dateFormat dateFromString:dateString];
}

+ (NSString*)stringFromDate:(NSDate*)date inFormat:(NSString*)format {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:format];
    return [dateFormat stringFromDate:date];
}

//+ (UIViewController*)presentedViewController {
//    UIViewController *presentedViewController = sRootViewController;
//    if (!presentedViewController) {
//        return nil;
//    }
//    while (YES) { 
//        UIViewController *viewController = nil;
//        if ([presentedViewController respondsToSelector:@selector(presentedViewController)]) {
//            viewController = [presentedViewController performSelector:@selector(presentedViewController)];
//        } else {
//            viewController = presentedViewController.modalViewController;
//        }
//        if (viewController) {
//            presentedViewController = viewController;
//        } else {
//            break;
//        }
//    }
//    return presentedViewController;
//}
//
//+ (void)setRootViewController:(UIViewController*)rootViewController {
//    sRootViewController = rootViewController;
//}
//
//+ (UIViewController*)rootViewController {
//    return sRootViewController;
//}

+ (NSString*)stringByRecoverXMLEscapesOfString:(NSString*)stringContainEscapes {
    NSMutableString *mutableString = [NSMutableString stringWithString:stringContainEscapes];
    [mutableString replaceOccurrencesOfString:@"&quot;" withString:@"\"" options:NSLiteralSearch range:NSMakeRange(0, mutableString.length)];
    [mutableString replaceOccurrencesOfString:@"&lt;" withString:@"<" options:NSLiteralSearch range:NSMakeRange(0, mutableString.length)];
    [mutableString replaceOccurrencesOfString:@"&gt;" withString:@">" options:NSLiteralSearch range:NSMakeRange(0, mutableString.length)];
    [mutableString replaceOccurrencesOfString:@"&amp;" withString:@"&" options:NSLiteralSearch range:NSMakeRange(0, mutableString.length)];
    [mutableString replaceOccurrencesOfString:@"&apos;" withString:@"'" options:NSLiteralSearch range:NSMakeRange(0, mutableString.length)];
    return mutableString;
}

+ (NSUInteger)numberOfOccurrencesOfSubString:(NSString*)subString options:(NSStringCompareOptions)mask inString:(NSString*)string {
    NSUInteger count = 0, length = [string length];
    NSRange range = NSMakeRange(0, length);
    while(range.location != NSNotFound)
    {
        range = [string rangeOfString:subString options:mask range:range];
        if(range.location != NSNotFound)
        {
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            count++; 
        }
    }
    return count;
}

+ (NSString *)md5ForString:(NSString*)str {
    if(self == nil || [str length] == 0)
        return nil;
    
    const char *value = [str UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    
    return outputString;
}

// From: http://www.cocoadev.com/index.pl?BaseSixtyFour
+ (NSString*)base64forData:(NSData*)theData {
	
	const uint8_t* input = (const uint8_t*)[theData bytes];
	NSInteger length = [theData length];
	
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
	
	NSInteger i,i2;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
		for (i2=0; i2<3; i2++) {
            value <<= 8;
            if (i+i2 < length) {
                value |= (0xFF & input[i+i2]);
            }
        }
		
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
	
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

+ (NSString*)connectStringFromArray:(NSArray*)stringArray usingSeperator:(NSString*)seperator {
    if (stringArray.count == 0) {
        return nil;
    }
    if (stringArray.count == 1) {
        return [stringArray objectAtIndex:0];
    }
    NSMutableString *str = [NSMutableString string];
    [stringArray enumerateObjectsUsingBlock:^(NSObject *obj, NSUInteger idx, BOOL *stop) {
            [str appendString:[obj description]];
            [str appendString:seperator];
    }];
    if (str.length > 0 && seperator.length > 0) {
        [str deleteCharactersInRange:NSMakeRange(str.length-seperator.length, seperator.length)];
    }
    return str;
}

+ (NSDate*)firstWeekdayDateOfDate:(NSDate*)date {
    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComonents = [currentCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:date];
    NSInteger substractWeekdayNumber = dateComonents.weekday - 2;
    NSInteger substractDayNumber = substractWeekdayNumber;
    if (substractWeekdayNumber < 0) {
        substractDayNumber += 7;
    }
    dateComonents.weekday -= substractWeekdayNumber;
    dateComonents.day -= substractDayNumber;
    return [currentCalendar dateFromComponents:dateComonents];
}

+ (UIFont*)fontWithURL:(NSURL*)url size:(CGFloat)size {
    if (!url) {
        return nil;
    }
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url);
	if (fontDataProvider == NULL) {
        return nil;
    }
	CGFontRef customFont = CGFontCreateWithDataProvider(fontDataProvider);
	CGDataProviderRelease(fontDataProvider);
	if (customFont == NULL) {
        return nil;
    }
    NSString *fontName = (__bridge NSString *)CGFontCopyFullName(customFont);
    CFErrorRef error;
    CTFontManagerRegisterGraphicsFont(customFont, &error);
    UIFont *font = [UIFont fontWithName:fontName size:size];
	CGFontRelease(customFont);
    return font;
}

+ (UIFont*)fontWithName:(NSString*)fileName ofType:(NSString*)type size:(CGFloat)size bundle:(NSBundle*)bundleOrNil {
    if (!fileName || !type) {
        return nil;
    }
    if (!bundleOrNil) {
        bundleOrNil = [NSBundle mainBundle];
    }
    NSString *fontPath = [bundleOrNil pathForResource:fileName ofType:type];
    if (!fontPath) {
        return nil;
    }
    NSURL *url = [NSURL fileURLWithPath:fontPath];
    return [CoolUtil fontWithURL:url size:size];
}

+ (NSString *)URLEncode:(NSString *)unencodedString {
    if ([CoolDevice systemVersion] >= 9.) {
        return [unencodedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; //编码
    }
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
    (NULL,
     (CFStringRef)unencodedString,
     NULL,
     (CFStringRef)@"!*'();:@&=+$,/?%#[]",
     kCFStringEncodingUTF8));
    
    return encodedString;
}

+ (NSString *)URLDecode:(NSString *)encodedString {
    if ([CoolDevice systemVersion] >= 9.) {
        return [encodedString stringByRemovingPercentEncoding]; //编码
    }
    if(encodedString == nil || [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] == nil) {
        return @"";
    } else {
        return [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
}

+ (CGFloat)contentHeighOfTextView:(UITextView*)textView {
    //    NSLog(@"textView.contentSize.height:%f", textView.contentSize.height);
    if ([CoolDevice systemVersion] < 7.f) {
        return textView.contentSize.height;
    }
    //    NSLog(@"%@", textView);
    //    [textView sizeToFit];
    //    [textView layoutIfNeeded];
    //    return textView.contentSize.height;
    //
    __block CGFloat height = 16.f;
    CGSize contrainedSize = CGSizeMake(textView.frame.size.width - textView.contentInset.left - textView.contentInset.right - 10.f, CGFLOAT_MAX);
    NSArray *lines = [textView.text componentsSeparatedByString:@"\n"];
    [lines enumerateObjectsUsingBlock:^(NSString *text, NSUInteger idx, BOOL *stop) {
        //CGSize size = [text sizeWithFont:textView.font constrainedToSize:contrainedSize];
        CGSize size = [text boundingRectWithSize:contrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:textView.font} context:nil].size;
        height += size.height;
    }];
    return roundf(height);
}

+ (CGFloat)contentHeighOfLabel:(UILabel*)label {
    if ([CoolDevice systemVersion] < 7.f) {
        return roundf([label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:0].size.height);
    }
    __block CGFloat height = 0.f;
    CGSize contrainedSize = CGSizeMake(label.bounds.size.width, CGFLOAT_MAX);
    NSArray *lines = [label.text componentsSeparatedByString:@"\n"];
    [lines enumerateObjectsUsingBlock:^(NSString *text, NSUInteger idx, BOOL *stop) {
        //CGSize size = [text sizeWithFont:label.font constrainedToSize:contrainedSize];
        CGSize size = [text boundingRectWithSize:contrainedSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font} context:nil].size;
        height += size.height;
    }];
    return roundf(height);
}

+ (CGSize)attributedTextSizeOfLabel:(UILabel *)label
{
    
    NSRange range = NSMakeRange(0, label.attributedText.length);
    NSDictionary *dic = [label.attributedText attributesAtIndex:0 effectiveRange:&range];   // 获取该段attributedString的属性字典
    CGRect titleRect = [label.text boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
    return titleRect.size;
}

+ (CGSize)sizeOfMultiLineLabelText:(NSString *)aLabelTextString font:(UIFont *)aLabelFont constrainedToSize:(CGSize)maxSize lineSpacing:(CGFloat)lineSpacing
{
    if (!aLabelTextString) {
        return CGSizeMake(0, 0);
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setLineBreakMode:NSLineBreakByCharWrapping];//NSLineBreakByCharWrapping
//    paragraphStyle.alignment = NSTextAlignmentJustified;
    
    return [aLabelTextString boundingRectWithSize:maxSize
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:aLabelFont, NSParagraphStyleAttributeName:paragraphStyle}
                                          context:nil].size;
}

+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content lineSpace:(CGFloat)lineSpacing
{
    return [self contentSpaceLine:content lineSpace:lineSpacing alignment:NSTextAlignmentLeft font:nil useUnderLineStyle:NO];//NSTextAlignmentLeft
}
+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content firstSpace:(CGFloat)firstSpace lineSpace:(CGFloat)lineSpacing{
    return [self contentSpaceLine:content firstLineHeadIndent:firstSpace lineSpace:lineSpacing alignment:NSTextAlignmentLeft font:nil useUnderLineStyle:NO];//NSTextAlignmentLeft
}

+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content lineSpace:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment font:(UIFont *)font
{
    if (content == nil) {
        return nil;
    }
    if (content.length <= 0) {
        return nil;
    }
    
    return [self contentSpaceLine:content lineSpace:lineSpacing alignment:alignment font:font useUnderLineStyle:NO];
}

+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content firstLineHeadIndent:(CGFloat)firstLineHeadIndent lineSpace:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment font:(UIFont *)font useUnderLineStyle:(BOOL)useUnderLine{
    if (content == nil) {
        return nil;
    }
    if (content.length <= 0) {
        return nil;
    }
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = alignment;
    //首行缩进
    paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;//NSLineBreakByCharWrapping
    [paragraphStyle setLineSpacing:lineSpacing];
    NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc] initWithString:content];
    [contentAttributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [content length])];
    if (font) {
        [contentAttributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [content length])];
    }
    
    if (useUnderLine) {
        [contentAttributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [content length])];
    } else {
        //        [contentAttributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:NSMakeRange(0, [content length])];
    }
    return contentAttributedString;
}

+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content lineSpace:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment font:(UIFont *)font useUnderLineStyle:(BOOL)useUnderLine
{
    return  [CoolUtil contentSpaceLine:content firstLineHeadIndent:0 lineSpace:lineSpacing alignment:alignment font:font useUnderLineStyle:useUnderLine];
}
+ (NSMutableAttributedString *)contentImageSpaceLine:(NSString *)content image:(UIImage*)image  imageFrame:(CGRect)frame lineSpace:(CGFloat)lineSpacing
{
    return [self contentImageSpaceLine:content image:image imageFrame:frame lineSpace:lineSpacing alignment:NSTextAlignmentJustified font:nil useUnderLineStyle:NO];//NSTextAlignmentLeft
}

+ (NSMutableAttributedString *)contentImageSpaceLine:(NSString *)content image:(UIImage*)image  imageFrame:(CGRect)frame lineSpace:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment font:(UIFont *)font useUnderLineStyle:(BOOL)useUnderLine
{
    if (content == nil) {
        return nil;
    }
    if (content.length <= 0) {
        return nil;
    }
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = alignment;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//NSLineBreakByCharWrapping;
    [paragraphStyle setLineSpacing:lineSpacing];
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    //使用一张图片作为Attachment数据
    attachment.image = image;
    //这里bounds的x值并不会产生影响
    attachment.bounds = frame;
    NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc] initWithString:content];
    [contentAttributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [content length])];
    [contentAttributedString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
    if (font) {
        [contentAttributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [content length])];
    }
    
    if (useUnderLine) {
        [contentAttributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [content length])];
    } else {
        [contentAttributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:NSMakeRange(0, [content length])];
    }
    return contentAttributedString;
}


+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content lineSpace:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment font:(UIFont *)font rangeString:(NSString *)rangeString tintColor:(UIColor *)color
{
    NSArray *rangeStringArray = nil;
    if (rangeString) {
        rangeStringArray = @[rangeString];
    }
    return [self contentSpaceLine:content lineSpace:lineSpacing alignment:alignment font:font rangeStringArray:rangeStringArray tintColor:color];
}

+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content lineSpace:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment font:(UIFont *)font rangeStringArray:(NSArray *)rangeStringArray tintColor:(UIColor *)color
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = alignment;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//NSLineBreakByCharWrapping;
    [paragraphStyle setLineSpacing:lineSpacing];
    NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc] initWithString:content];
    [contentAttributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [content length])];
    
    if (font) {
        [contentAttributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [content length])];
    }
    
    [contentAttributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:NSMakeRange(0, [content length])];
    
    [rangeStringArray enumerateObjectsUsingBlock:^(NSString *rangeString, NSUInteger idx, BOOL *stop){
        NSString *contentCopy = [content copy];
        NSRange range = [content rangeOfString:rangeString];
         [contentAttributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
        
        NSRange desOrigin = range;
        while (range.location != NSNotFound) {
            NSRange subRange = [self substring:contentCopy rang:range rangeString:rangeString];
            if (subRange.location == NSNotFound) {
                break;
            }
            contentCopy = [contentCopy substringFromIndex:(subRange.location+subRange.length)];
            desOrigin = NSMakeRange(desOrigin.location+desOrigin.length+subRange.location, subRange.length);
            [contentAttributedString addAttribute:NSForegroundColorAttributeName value:color range:desOrigin];
        }
    }];
    
    return contentAttributedString;
}

+ (NSMutableAttributedString *)contentSpaceLine:(NSString *)content lineSpace:(CGFloat)lineSpacing alignment:(NSTextAlignment)alignment font:(UIFont *)font rangeArray:(NSArray *)rangeArray tintColor:(UIColor *)color
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = alignment;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//NSLineBreakByCharWrapping;
    [paragraphStyle setLineSpacing:lineSpacing];
    NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc] initWithString:content];
    [contentAttributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [content length])];
        
    if (font) {
        [contentAttributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [content length])];
    }

    [contentAttributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:NSMakeRange(0, [content length])];

    [rangeArray enumerateObjectsUsingBlock:^(NSValue *value, NSUInteger idx, BOOL *stop){
        NSRange range = value.rangeValue;
        [contentAttributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
    }];
    
    return contentAttributedString;
}

+ (NSRange)substring:(NSString *)content rang:(NSRange)range rangeString:(NSString *)rangeString
{
    content = [content substringFromIndex:(range.location+range.length)];
    return [content rangeOfString:rangeString];
}

+ (NSString *)formatterText:(NSString *)text
{
    if ([text isKindOfClass:[NSNull class]]) {
        return @"--";
    }
    else if (text && text.length > 0) return text;
    else return @"--";
}

+ (NSString *)formatterText:(NSString *)text withDefaultText:(NSString *)defaultText
{
    if ([text isKindOfClass:[NSNull class]]) {
        if (defaultText) {
            return defaultText;
        }
        return @"--";
    } else if (text && text.length > 0) {
        return text;
    } else {
        if (defaultText) {
            return defaultText;
        }
        return @"--";
    };
}

+ (NSUInteger)formatterType:(NSString *)type
{
    return type.integerValue;
}

+ (UILabel  *)creatNormalLabel:(UIColor *)textColor align:(NSTextAlignment)textAlignment font:(UIFont *)textFont parent:(UIView *)superView
{
    UILabel   *commonLabel  = [[UILabel alloc] init];
    commonLabel.textColor = textColor;
    commonLabel.backgroundColor = [UIColor clearColor];
    if (textAlignment) commonLabel.textAlignment = textAlignment;
    if (textFont) commonLabel.font = textFont;
    if (superView) {
        [superView addSubview:commonLabel];
    }
    return commonLabel;
}

+ (UIButton *)createButton:(NSString *)title titleFont:(UIFont *)font titleColor:(UIColor *)tlColor img:(UIImage *)img bg:(UIImage *)bgImg parent:(UIView *)superView
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (bgImg) {
        [button setBackgroundImage:bgImg forState:UIControlStateNormal];
    }
    if (img) [button setImage:img forState:UIControlStateNormal];
    if (title) {
        [button setTitle:title forState:UIControlStateNormal];
    }
    if (tlColor) {
        [button setTitleColor:tlColor  forState:UIControlStateNormal];
        [button setTitleColor:tlColor  forState:UIControlStateHighlighted];
    }
    if (font) {
          button.titleLabel.font = font;
    }
    if (superView) {
        [superView addSubview:button];
    }
    return button;
}

//返回 分割线 label
+ (UIView *)creatTableSeparatorLineParent:(UIView *)superView
{
    UIView *lineSeparator  = [UIView new];
    lineSeparator.backgroundColor = [UIColor colorWithHexString:LIGHT_GRAY_LINE_COLOR];
    [superView addSubview:lineSeparator];
    return lineSeparator;
}

@end
